#!/usr/bin/python

import wx
import wx.stc
import wx.stc as stc

FILLER='\nclass MainPanel(wx.Panel):\n\n\tdef __init__(me,parent):\n\t\twx.Panel.__init__(me,parent)\n\t\t\n\t\tme.text=wx.stc.StyledTextCtrl(me)\n\t\t\n\t\tsz=wx.BoxSizer(wx.VERTICAL)\n\t\t\n\t\tme.SetSizer(sz)\n\t\t\n\t\tsz.Add(me.text,1,wx.EXPAND)\n\t\tme.SetAutoLayout(True)\n\t\t\n\t\tme.text.AddText(FILLER)\n\n\t\t\nclass MainFrame(wx.Frame):\n\n\tdef __init__(me):\n\t\t\t\n\t\twx.Frame.__init__(me,parent=None)\n\t\tMainPanel(parent=me)\n\t\t\n\napp = wx.PySimpleApp()\nframe = MainFrame()\nframe.Show()\nframe.Centre()\napp.MainLoop()\n'

import math

from common import EventBus
	
class BraceMatchController:
	def __init__(me,doc):
		me.state_displaying_match=False
		me.edit=doc.edit
		#doc.Bind(wx.stc.EVT_STC_UPDATEUI,me.on_updateui)
		EventBus.listen_for(doc,me.on_updateui,doc.MSK_UPDATEUI)
		
	def undisplay_prev_match(me):
		if not me.state_displaying_match: return
		
		#me.edit.BraceBadLight(-1)
		me.edit.BraceHighlight(-1,-1) # this appears to clear both highlights out, good or bad

		me.state_displaying_match=False

	def display_match(me):
		pos1=me.edit.GetCurrentPos()-1
		
		if pos1<0: return # 1st caret position in file
		
		c=chr(me.edit.GetCharAt(pos1))
		
		if c not in '()[]{}<>': return
		
		pos2=me.edit.BraceMatch(pos1)
		
		if pos2==-1:
			#print 'bad',pos1
			me.edit.BraceBadLight(pos1)
		else:
			#print 'good',pos1,pos2
			me.edit.BraceHighlight(pos1,pos2)
			
		me.state_displaying_match=True
		
	def on_updateui(me):
		me.undisplay_prev_match()
		me.display_match()

class MainPanel(wx.Panel):
	
	MSK_UPDATEUI=0x1

	def __init__(me,parent):
		wx.Panel.__init__(me,parent)
		
		me.edit=wx.stc.StyledTextCtrl(me)
		
		sz=wx.BoxSizer(wx.VERTICAL)
		
		me.SetSizer(sz)
		
		sz.Add(me.edit,1,wx.EXPAND)
		me.SetAutoLayout(True)
		
		me.edit.StyleSetSpec(stc.STC_STYLE_BRACELIGHT,  "fore:#FFFFFF,back:#0000FF,bold")
		me.edit.StyleSetSpec(stc.STC_STYLE_BRACEBAD,    "fore:#000000,back:#FF0000,bold")
		
		EventBus.add_broadcaster(me)
		
		me.Bind(stc.EVT_STC_MODIFIED, me.OnTextModified)
		me.Bind(stc.EVT_STC_PAINTED, me.OnTextPainted)
		me.Bind(stc.EVT_STC_CHARADDED, me.OnTextCharAdded)
		me.Bind(stc.EVT_STC_UPDATEUI,lambda ev: EventBus.post(me,me.MSK_UPDATEUI))
			
		me.edit.AddText(FILLER)
		
		me.CTRL_brace_match = BraceMatchController(me)


	def OnTextModified(me,e):
		pass
		
	def OnTextPainted(me,e):
		pass		
		
	def OnTextCharAdded(me,e):
		pass
		
class MainFrame(wx.Frame):

	def __init__(me):
			
		wx.Frame.__init__(me,parent=None)
		me.panel=MainPanel(parent=me)
		
		mb=wx.MenuBar()
		me.SetMenuBar(mb)
		m=wx.Menu()
		mb.Append(m,"&Menu")
		id=wx.NewId()
		m.Append(id,'Do Something')
		me.Bind(wx.EVT_MENU,me.OnMenuDoSomething,id=id)
		
		me.toggle=True
		
	def OnMenuDoSomething(me,e):
		me.toggle=not me.toggle
		
		

app = wx.PySimpleApp()
frame = MainFrame()
frame.Show()
frame.Centre()
app.MainLoop()